<?php
/*
---------------------------------------------------------
														+
名称:易通支付通道										+
														+
控制器名称:YiTongController								+
														+
日期:2017-10-11											+
														+
作者:小翁												+
														+
---------------------------------------------------------
*/
namespace Pay\Controller;

use Common\Common\Api\Order;
use Common\Common\Api\Ordermember;
use Common\Common\Api\Redis\Channel;
use Common\Common\Api\Redis\Product;

class YuchengController extends PayController{
    protected $config;
    protected $key;
    protected $url;

    public function pay($array){
        $this->config = Channel::getInstance()->getById($array['channel']);
        if(!$this->config){
            $this->showmessage('通道错误!',['code'=>'035']);
        }

        $product = Product::getInstance()->getById(I("request.pay_bankcode",0,"intval"));
        if(!$product){
            $this->showmessage('未找到支付产品!',['code'=>'035']);
        }

        $parameter = array(
            'code' => $this->config['code'], // 通道名称
            'title' => $this->config['title'],
            'exchange' => 1, // 金额比例
            'gateway' => $this->config['gateway'],
            'orderid' => createOrderId(),
            'out_trade_id' => I("request.pay_orderid"),
            'body' => 'pay',
            'channel'=>$array
        );

        $return = $this->orderadd( $parameter );

        $data = array();

        $data['outNo'] = $return['orderid'];
        $data['outAmount'] = intval($return['amount'] * 100);
        $data['outIP'] = $_SERVER['REMOTE_ADDR'];
        $data['outAppName'] = "apple";
        $data['outAppType'] = "AND_WAP";
        $data['outAppSymbol'] = 'com.tencent.tmgp.sgame';
        switch($this->config['paytype']){
            //微信
            case 1:
                $data['outTag'] = 'WXPAY';
                break;
            //支付宝
            case 3:
                $data['outTag'] = 'ZFBPAY';
                break;
            //支付宝H5
            case 4:
                $data['outTag'] = 'ZFBPAY';
                break;
            default:
                $this->showmessage('不支持此产品!',['code'=>'035']);
        }
        $data['outNotifyUrl'] = $return['notifyurl'];
        $data['outReturnUrl'] = $return['callbackurl'];
        $data['outDesc'] = $return['orangle'];

        $json = json_encode($data);
        $str = $this->aes_encode($json, $this->config['signkey']);

        $url = $this->config['gateway'] . "?lyOpenId=". $this->config['mch_id'] . "&data=" . $str;

        $res = $this->curl_gets($url);

        $res = json_decode($res,true);
        if(!$res['out_success']){
            if($res['out_message']){
                $this->showmessage($res['out_message']);
            }

            $this->showmessage("获取支付链接失败");
        }

        header("location: {$res['out_message']}");
    }

    //通知
    public function notifyurl(){
        //file_put_contents("a.txt",var_export($_POST,true)."\r\n\r\n");
        //file_put_contents("a.txt",var_export($_GET,true."\r\n\r\n"), FILE_APPEND);
        //file_put_contents("a.txt", file_get_contents('php://input')."\r\n\r\n", FILE_APPEND);
        //file_put_contents("a.txt",date("Y-m-d H:i:s",time()) . "\r\n", FILE_APPEND);

        $p = I("get.");

        /*$p = array (
            'lyOpenId' => '20181016',
            'data' => 'CE7506B90BCC37C736671427603D5BB0C21EA976BB82FF64DD74CF9FB86131964B8F88369001ECB62561BFF75E71866FFB1EB95FA849B8F4F4ED89F8440B467D8BAE32A0411CDDF8E12BB90648E8C222534237A4C41FADDBE36E988835F1FFCC753D056AD5D04267D45E76C6F96CCFB5C984A42AF1548A389139DBE3BAFF3EB8731AEACB63E3D0C9FDEE14EA2609103754366F3A2940550BA5267A3246372DD2B42BC56EA617AF6EEDAA1022DDF4FA40',
        );*/

        //获取渠道信息
        $this->config = M("Channel")->where(array('code'=>'Yucheng'))->find();

        $data = $this->aes_decode($p['data'], $this->config['signkey']);

        $data = json_decode($data, true);
        if(empty($data)){
            echo "data wrong"; exit;
        }
        /*
         * Array
            (
                [outNo] => 201810171414302196129
                [outAmount] => 1000
                [outSucceedTime] => 2018-10-17 14:15:30
                [outPayNo] => 2018101722001455940561366935
                [lyOpenId] => 20181016
                [status] => 1
            )
         */

        //获取订单信息
        $orderid = $data['outNo'];
        $find = M("Order")->where(array("pay_orderid"=>$orderid))->find();

        if(!$find){
            echo 'order_not_found'; exit;
        }
        //保存回调数据
        M("Order")->where(array("pay_orderid"=>$p['busi_order_no']))->save(array("server_return"=> http_build_query(I("get.")),"pay_orderid_rd"=>$data['outPayNo']));

        if(intval($data['status']) != 1){
            exit("pay_fail");
        }

        //处理支付
        //$this->EditMoney($find['pay_orderid'],"Yucheng",0);

        //回调成功
        //echo 'success'; exit;
        $this->async($find['pay_orderid'],'success');
    }

    public function callBackUrl(){

        echo '支付成功'; exit;
    }


    // AES加密
    function aes_encode($input, $key){
        $size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
        $input = $this->pkcs5_pad($input, $size);
        $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, '');
        $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
        mcrypt_generic_init($td, $key, $iv);
        $data = mcrypt_generic($td, $input);
        mcrypt_generic_deinit($td);
        mcrypt_module_close($td);
        $data = strtoupper(bin2hex($data));
        return $data;
    }

    // AES解密
    function aes_decode($sStr, $sKey){
        $sStr = hex2bin($sStr);
        $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $sKey, $sStr, MCRYPT_MODE_ECB);
        $dec_s = strlen($decrypted);
        $padding = ord($decrypted[$dec_s - 1]);
        $decrypted = substr($decrypted, 0, - $padding);
        return $decrypted;
    }

    // AES算法
    function pkcs5_pad($text, $blocksize){
        $pad = $blocksize - (strlen($text) % $blocksize);
        return $text . str_repeat(chr($pad), $pad);
    }

    function curl_gets($url, $data = null){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (! empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }
}